import re, collections
#把语料库中的单词全部转换成小写，然后去掉特色字符
def words(text): return re.findall('[a-z]+', text.lower())

def train(features):
    model = collections.defaultdict(lambda: 1)
    for f in features:
       model[f] += 1

    return model

NWORDS = train(words(open('big.txt').read()))
print(len(NWORDS))
print('----------------------------')
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def editsl(word):
     n = len(word)
     return set([word[0:i] + word[i+1:] for i in range(n)] +
                [word[0:i] + word[i+1] + word[i] + word[i+2:] for i in range(n-1)] +  #删除
                [word[0:i] + c + word[i+1:] for i in range(n) for c in alphabet] +      #转换
                [word[0:i] + c + word[i:] for i in range(n+1) for c in alphabet])    #替换
word='apple'
print(editsl(word))

# def edits2(word):
#     return set(e2 for el in editsl(word) for e2 in editsl(el))
def known_edits2(word):
    return set(e2 for el in editsl(word) for e2 in editsl(el) if e2 in NWORDS.keys())

print(known_edits2('morw'))

def known(words):
    return set(w for w in words if w in NWORDS)

def correct(word):
    candidates = known([word]) or known(editsl(word)) or known_edits2(word) or [word]
    return max(candidates, key=lambda w: NWORDS[w])

print(correct(('morw')))
